/**
 * @author chelfinn
 * date 2018-9-12
 *
 */
var url = getApp().globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   * address_id 地址id
   * key         用户标识
   * buyer_id    如果是参团，才会有这个id
   * status      选中当前状态，1普通购买，2拼团包括新建团和参团购买，3砍价购买
   * count       商品数量
   * payment_code
   * pay_sn      购买第二步返回的订单号，用于支付
   * pintuan     是否为拼团订单，拼团填1
   * pintuan_id  不为空时，就是参团的id了
   */
  data: {
    show: false,     //显示设置，false隐藏，true显示
    selectData: ["工作日节假日均可送货", "工作日送货", "节假日送货"],    //下拉列表显示项
    index: 0,    //显示项下下标，
    key: wx.getStorageSync('key'),
    messages: '',
    addrShow: false, //是否显示新增地址
    addressinfo: {},
    count: '',
    address_info: false,
    payment_code: false,
    pay_sn: false,
    pintuan: false,
    request_url: '',  //请求地址
    menu_info: {},  //购买第一步返回的数据
    goodsArr: [], //一个订单所有店铺的数据
    cart_id: '',  // 购物车id
    freight: 0.00, //运费
    counpous: 0.00, //代金券/红包
    goods_img: '',
    store_id: 0,
    is_pintaun: 0,
    showCounps: true,     // 优惠券显示和影藏

  },
  // 点击下拉显示框
  selectTap() {
    this.setData({
      show: !this.data.show
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      index: Index,
      show: !this.data.show
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    if (options.is_pintuan) {
      this.setData({
        "is_pintuan": options.is_pintuan,
      })
    };
    if (options.is_kanjia) {
      this.setData({
        "is_kanjia": options.is_kanjia,
      })
    };
    if (options.buyer_id) {
      this.setData({
        buyer_id: options.buyer_id
      })
    };
    if (options.log_id) {
      this.setData({
        log_id: options.log_id
      })
    };
    this.setData({
      "request_url": getApp().globalData.ApiUrl,
      "ifcart": options.ifcart,
      "cart_id": options.cart_id,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (optios) {
    var that = this;
    //获取收货地址
    this.getAddress();
  },

  /**
   * @author chelfinn 
   * date 2018-9-13
   * 改变收货地址
   */
  changeAddr: function () {
    wx.navigateTo({
      url: '/pages/about-address/address/index',
    });
  },
  /**
   * @author chelfinn 
   * date 2018-9-13
   * 跳转到新增地址
   */
  addAddr: function () {
    wx.navigateTo({
      url: '/pages/about-address/add-new-addr/index',
    });
  },
  /**
   * @author chelfinn 
   * date 2018-9-12
   * 获取收货地址
   */
  getAddress: function () {
    var that = this;
    // 获取收货地址列表
    wx.request({
      url: url + '/mobile/index.php?act=member_address&op=address_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        key: wx.getStorageSync('key'),
      },
      success: (res) => {
        if (res.data.code == 200) {
          var address_list = res.data.datas.address_list;
          for (var i in address_list) {
            if (address_list[i].is_default == '1') {
              that.setData({
                addressinfo: address_list[i],
                addrShow: true
              });
            }
          }
          //购买流程第一步
          that.step1();
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  /**
   * 购买流程第一步
   * @author chelfinn
   * date 2018-9-12
   */
  step1: function (ops) {
    var that = this;
    wx.showLoading({
      title: '加载中，请稍后...',
    });
    var data = {
      "key": wx.getStorageSync('key'),
      "ifcart": this.data.ifcart,
      "cart_id": this.data.cart_id,
      "address_id": that.data.addressinfo.address_id,
    };
    if (this.data.is_pintuan) {
      data.pintuan = 1
    } 
    if (this.data.is_kanjia) {
      data.kanjia = 1
    }
    wx.request({
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      method: "POST",
      url: `${that.data.request_url}/mobile/index.php?act=member_buy&op=buy_step1`,
      data: data,
      success: function (res) {
        if (res.data.code == 200) {
          wx.hideLoading();
          var arr = [];
          var arrList = [];
          var freight = 0;
          var prices = 0;  // 所有没有计算运费和优惠券商品总价
          var list = res.data.datas;
          var sum;    // 该笔订单总价
          var rpt_list = list.rpt_list;
          var rpt_price = 0;
          var store_list = list.store_cart_list;
          var zong = list.order_amount;
          for (var store_id in store_list) {
            arr.push(store_list[store_id].goods_list);   //商品信息
            arrList.push(store_list[store_id]);
          };
          for (var i in arr) {
            for (var n in arr[i]) {
              freight += parseFloat(arr[i][n].goods_freight);  //运费
              prices += parseFloat(arr[i][n].goods_price * arr[i][n].goods_num);
            }
          }
          sum = freight + prices;
          if (rpt_list.length != 0) {
            for (var rpt in rpt_list) {
              if (sum >= rpt_list[rpt].rpacket_limit) {
                rpt_price = rpt_list[rpt].rpacket_price;   //  优惠券
                that.setData({
                  showCounps: true
                })
              } else {
                that.setData({
                  showCounps: false
                }) 
              }; 
              var rpt_t_id = rpt_list[rpt].rpacket_t_id + '|' + rpt_price;
              that.setData({
                rpt_t_id: rpt_t_id
              })
            }
          } else {
            that.setData({
              showCounps: false
            })
          }
          that.setData({
            menu_info: list,
            arrList: arrList,
            info_list: arr,
            goods_freight: freight,
            total: zong,
            counpous: rpt_price,
          })
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '人太多啦',
        })
      }
    });
  },
  //订单留言鼠标事件

  bindSelectBlur: function (e) {
    var messages = e.detail.value;
    this.setData({
      messages: messages
    });
  },
  //提交订单
  // status      选中当前状态，1普通购买，2拼团包括新建团和参团购买，3砍价购买
  submit: function (e) {
    var that = this;
    var key = wx.getStorageSync('key');
    if (!key) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            });
          }
        }
      });
      return
    }
    var address_id = that.data.addressinfo.address_id;
    if (!address_id) {
      wx.showToast({
        title: '请填写收货地址',
        icon: 'none',
        duration: 2000
      });
      return
    }
    getApp().saveFormId(e.detail.formId);
    var that = this;
    var rpacket;
    if (that.data.menu_info.rpacket_t_id) {
      rpacket = `${that.data.menu_info.rpacket_t_id}|${that.data.menu_info.rpacket_price}`;
    } else {
      rpacket = '';
    }
    var datas = {
      "key": wx.getStorageSync("key"),
      "cart_id": that.data.cart_id,//格式，商品id+|+数量
      "ifcart": that.data.ifcart,//购物车购买为1      
      "address_id": that.data.addressinfo.address_id,//进入页面要给他默认选中一个地址，这里要加载的时候设定      
      "vat_hash": that.data.menu_info.vat_hash,
      "offpay_hash": that.data.menu_info.address_api.offpay_hash,
      "offpay_hash_batch": that.data.menu_info.address_api.offpay_hash_batch,
      "pay_name": 'online',
      "invoice_id": 0,
      "voucher": '',
      "pd_pay": 0,
      "password": '',
      "fcode": '',
      "rcb_pay": 0,
      "rpt": rpacket,
      "reciver_date_msg": that.data.selectData[that.data.index],
      "pay_message": `${that.data.menu_info.vat_hash}|${that.data.messages}`,
      
    };
    if (that.data.is_pintuan) {
      if (that.data.counpous != 0) datas.rpt = that.data.rpt_t_id;
      datas.pintuan = 1;
      datas.buyer_id = that.data.menu_info.address_info.member_id;
    } else if (that.data.is_kanjia) {
      if (that.data.counpous != 0) datas.rpt = that.data.rpt_t_id;
      datas.kanjia = 1
    } else {
      if (that.data.counpous != 0) datas.rpt = that.data.rpt_t_id;
      datas.buyer_id = that.data.menu_info.address_info.member_id;
    };
    if (that.data.buyer_id) {
      datas.buyer_id = that.data.buyer_id;
    };
    if (that.data.log_id) {
      datas.log_id = that.data.log_id;
    }
    /**
     * 如下区分普通订单，拼团，砍价，
     */
    // switch (that.data.status) {
    //   case '3':
    //     datas['kanjia'] = 1;
    //     break;
    //   case '2':
    //     datas['pintuan'] = 1;
        
    //     break;
    // }
    //判断是否有地址，没有提示用户添加
    if (that.data.addressinfo.address_id == 0) {
      wx.showModal({
        title: '提示',
        content: '未添加收货地址，请添加',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/about-address/get-address/index',
            });
          }
        }
      });
      return false;
    }
    wx.request({
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      method: "POST",
      url: `${that.data.request_url}/mobile/index.php?act=member_buy&op=buy_step2`,
      data: datas,
      success: function (e) {
        if (e.data.code == 200) {
          that.setData({
            "pay_sn": e.data.datas.pay_sn,
            "payment_code": e.data.datas.payment_code
          });
          var status = that.data.status;
          that.payNow(status);
        };
        if (e.data.code == 400) {
          if (e.data.login == 0 && e.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: e.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '人太多啦',
          duration: 1500,
          icon: 'none'
        })
      }
    })
    var key = wx.getStorageSync('key');
    if (!key) {
      wx.redirectTo({
        url: '/pages/authorize/index'
      })
    }
    this.setData({
      showView: true
    })

  },
  /**
   * 微信支付
   * @author Harris
   * @date 2018-09-10
   */
  payNow: function (status) {
    var that = this;
    wx.request({
      url: `${that.data.request_url}/mobile/index.php?act=member_payment&op=applet_pay`,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        "key": wx.getStorageSync("key"),
        "pay_sn": this.data.pay_sn
      },
      method: 'POST',
      success: function (res) {
        wx.requestPayment({
          'timeStamp': res.data.datas.timeStamp,
          'nonceStr': res.data.datas.nonceStr,
          'package': res.data.datas.package,
          'signType': 'MD5',
          'paySign': res.data.datas.paySign,
          'success': function (res) {
            if (that.data.is_pintuan) {
              wx.redirectTo({
                url: '/pages/my-group/index?buyer_id=' + that.data.menu_info.address_info.member_id + '&pay_sn=' + that.data.pay_sn,
              });
            } else if (that.data.is_kanjia) {
              wx.redirectTo({
                url: '/pages/my-bargain/index?buyer_id=' + that.data.menu_info.address_info.member_id + '&pay_sn=' + that.data.pay_sn,
              });
            } else {
              wx.redirectTo({
                url: '/pages/order/order-list/index',
              });
            };
          },
          'fail': function (res) {
            if (res.errMsg == 'requestPayment:fail cancel') {
              wx.showToast({
                title: '取消付款',
                icon: 'none',
                duration: 800
              });
              wx.navigateTo({
                url: '/pages/order/be-paid/index',
              })
            }
          }
        });
      },
      fail: function (res) {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  /*
   *@author Harris
   *@date 2018-09-04
   *用户留言
   */
  message: function (e) {
    this.setData({ message: e.detail.value });
  },
  errorTap: function () {
    this.setData({
      showView: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})